package com.ruoyi.web.controller.gcgl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gcgl.domain.GcProject;
import com.ruoyi.gcgl.domain.GysptDeilikq;
import com.ruoyi.gcgl.domain.GysptKqproject;
import com.ruoyi.gcgl.domain.GysptKqworks;
import com.ruoyi.gcgl.domain.GysptKqygtj;
import com.ruoyi.gcgl.domain.GysptPerson;
import com.ruoyi.gcgl.service.IGcProjectService;
import com.ruoyi.gcgl.service.IGysptDeilikqService;
import com.ruoyi.gcgl.service.IGysptKqprojectService;
import com.ruoyi.gcgl.service.IGysptKqworksService;
import com.ruoyi.gcgl.service.IGysptKqygtjService;
import com.ruoyi.gcgl.service.IGysptPersonService;

/**
 * 考勤管理Controller
 * 
 * @author ruoyi
 * @date 2024-12-07
 */
@Controller
@RequestMapping("/gcgl/kqproject")
public class GysptKqprojectController extends BaseController
{
    private String prefix = "gcgl/kqproject";

    @Autowired
    private IGysptKqprojectService gysptKqprojectService;
    @Autowired
    private IGysptKqworksService gysptKqworksService;
    @Autowired
    private IGcProjectService gcProjectService;
    @Autowired
    private IGysptPersonService gysptPersonService;
    @Autowired
    private IGysptKqygtjService gysptKqygtjService;
    @Autowired
    private IGysptDeilikqService gysptDeilikqService;

    @RequiresPermissions("gcgl:kqproject:view")
    @GetMapping()
    public String kqproject()
    {
        return prefix + "/kqproject";
    }

    /**
     * 查询考勤管理列表
     */
    @RequiresPermissions("gcgl:kqproject:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(GysptKqproject gysptKqproject)
    {
        startPage();
        gysptKqproject.setDeleteFlag(1);
        List<GysptKqproject> list = gysptKqprojectService.selectGysptKqprojectList(gysptKqproject);
        return getDataTable(list);
    }

    /**
     * 导出考勤管理列表
     */
    @RequiresPermissions("gcgl:kqproject:export")
    @Log(title = "考勤管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(GysptKqproject gysptKqproject)
    {
        List<GysptKqproject> list = gysptKqprojectService.selectGysptKqprojectList(gysptKqproject);
        ExcelUtil<GysptKqproject> util = new ExcelUtil<GysptKqproject>(GysptKqproject.class);
        return util.exportExcel(list, "考勤管理数据");
    }

    /**
     * 新增考勤管理
     */
    @GetMapping("/add")
    public String add(ModelMap mmap){
    	GysptDeilikq gysptDeilikq = new GysptDeilikq();
    	gysptDeilikq.setDeleteFlag(1);
    	List<GysptDeilikq> deililis = gysptDeilikqService.selectGysptDeilikqList(gysptDeilikq);
    	mmap.put("deililis", deililis);
        return prefix + "/add";
    }

    /**
     * 新增保存考勤管理
     */
    @RequiresPermissions("gcgl:kqproject:add")
    @Log(title = "考勤管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GysptKqproject gysptKqproject){
    	try {
    		gysptKqproject.setStatus(0);
        	gysptKqproject.setDeleteFlag(1);
        	gysptKqproject.setCreateUser(getLoginName());
        	gysptKqproject.setUpdateUser(getLoginName());
        	gysptKqproject.setCreateAt(new Date());
        	gysptKqproject.setUpdateAt(new Date());
        	gysptKqprojectService.insertGysptKqproject(gysptKqproject);
        	
        	if(gysptKqproject.getItems()!=null && gysptKqproject.getItems().size()>0){
        		for(GysptKqworks work:gysptKqproject.getItems()){
        			work.setGysptProjectid(gysptKqproject.getGysptProjectid());
        			work.setProjectId(gysptKqproject.getId());
        			work.setStatus(0);
        			work.setDeleteFlag(1);
        			work.setCreateUser(getLoginName());
        			work.setUpdateUser(getLoginName());
        			work.setCreateAt(new Date());
        			work.setUpdateAt(new Date());
        			gysptKqworksService.insertGysptKqworks(work);
        		}
        	}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return toAjax(0);
		}
    	
        return toAjax(1);
    }
    
    @RequiresPermissions("gcgl:kqproject:add")
    @Log(title = "考勤管理", businessType = BusinessType.INSERT)
    @PostMapping("/addSubmit")
    @ResponseBody
    public AjaxResult addSubmitSave(GysptKqproject gysptKqproject){
    	try {
    		gysptKqproject.setStatus(1);
        	gysptKqproject.setDeleteFlag(1);
        	gysptKqproject.setCreateUser(getLoginName());
        	gysptKqproject.setUpdateUser(getLoginName());
        	gysptKqproject.setCreateAt(new Date());
        	gysptKqproject.setUpdateAt(new Date());
        	gysptKqprojectService.insertGysptKqproject(gysptKqproject);
        	
        	if(gysptKqproject.getItems()!=null && gysptKqproject.getItems().size()>0){
        		for(GysptKqworks work:gysptKqproject.getItems()){
        			work.setGysptProjectid(gysptKqproject.getGysptProjectid());
        			work.setProjectId(gysptKqproject.getId());
        			work.setStatus(1);
        			work.setDeleteFlag(1);
        			work.setCreateUser(getLoginName());
        			work.setUpdateUser(getLoginName());
        			work.setCreateAt(new Date());
        			work.setUpdateAt(new Date());
        			gysptKqworksService.insertGysptKqworks(work);
        		}
        	}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return toAjax(0);
		}
    	
        return toAjax(1);
    }
    
    /**
     * 修改考勤管理
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap){
        GysptKqproject gysptKqproject = gysptKqprojectService.selectGysptKqprojectById(id);
        mmap.put("gysptKqproject", gysptKqproject);
        
        GysptDeilikq gysptDeilikq = new GysptDeilikq();
    	gysptDeilikq.setDeleteFlag(1);
    	List<GysptDeilikq> deililis = gysptDeilikqService.selectGysptDeilikqList(gysptDeilikq);
    	mmap.put("deililis", deililis);
        return prefix + "/detail";
    }

    /**
     * 修改考勤管理
     */
    @RequiresPermissions("gcgl:kqproject:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap){
        GysptKqproject gysptKqproject = gysptKqprojectService.selectGysptKqprojectById(id);
        
        GysptKqworks gysptKqworks = new GysptKqworks();
        gysptKqworks.setProjectId(id);
        List<GysptKqworks> items = gysptKqworksService.selectGysptKqworksList(gysptKqworks);
        gysptKqproject.setItems(items);
        mmap.put("gysptKqproject", gysptKqproject);
        
        GysptDeilikq gysptDeilikq = new GysptDeilikq();
    	gysptDeilikq.setDeleteFlag(1);
    	List<GysptDeilikq> deililis = gysptDeilikqService.selectGysptDeilikqList(gysptDeilikq);
    	mmap.put("deililis", deililis);
    	
        return prefix + "/edit";
    }

    /**
     * 修改保存考勤管理
     */
    @RequiresPermissions("gcgl:kqproject:edit")
    @Log(title = "考勤管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GysptKqproject gysptKqproject){
    	try {
    		gysptKqproject.setStatus(0);
        	gysptKqproject.setUpdateUser(getLoginName());
        	gysptKqproject.setUpdateAt(new Date());
    		gysptKqprojectService.updateGysptKqproject(gysptKqproject);
    		
    		gysptKqworksService.deleteGysptKqworksById(gysptKqproject.getId());
    		
    		if(gysptKqproject.getItems()!=null && gysptKqproject.getItems().size()>0){
        		for(GysptKqworks work:gysptKqproject.getItems()){
        			work.setGysptProjectid(gysptKqproject.getGysptProjectid());
        			work.setProjectId(gysptKqproject.getId());
        			work.setStatus(0);
        			work.setDeleteFlag(1);
        			work.setCreateUser(getLoginName());
        			work.setUpdateUser(getLoginName());
        			work.setCreateAt(new Date());
        			work.setUpdateAt(new Date());
        			gysptKqworksService.insertGysptKqworks(work);
        		}
        	}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return toAjax(0);
		}
    	
        return toAjax(1);
    }
    
    @RequiresPermissions("gcgl:kqproject:edit")
    @Log(title = "考勤管理", businessType = BusinessType.UPDATE)
    @PostMapping("/editSubmit")
    @ResponseBody
    public AjaxResult editSubmitSave(GysptKqproject gysptKqproject){
    	try {
    		gysptKqproject.setStatus(1);
        	gysptKqproject.setUpdateUser(getLoginName());
        	gysptKqproject.setUpdateAt(new Date());
    		gysptKqprojectService.updateGysptKqproject(gysptKqproject);
    		
    		gysptKqworksService.deleteGysptKqworksById(gysptKqproject.getId());
    		
    		if(gysptKqproject.getItems()!=null && gysptKqproject.getItems().size()>0){
        		for(GysptKqworks work:gysptKqproject.getItems()){
        			work.setGysptProjectid(gysptKqproject.getGysptProjectid());
        			work.setProjectId(gysptKqproject.getId());
        			work.setStatus(1);
        			work.setDeleteFlag(1);
        			work.setCreateUser(getLoginName());
        			work.setUpdateUser(getLoginName());
        			work.setCreateAt(new Date());
        			work.setUpdateAt(new Date());
        			gysptKqworksService.insertGysptKqworks(work);
        		}
        	}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return toAjax(0);
		}
    	
        return toAjax(1);
    }

    /**
     * 删除考勤管理
     */
    @RequiresPermissions("gcgl:kqproject:remove")
    @Log(title = "考勤管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(gysptKqprojectService.deleteGysptKqprojectByIds(ids));
    }
    
    //-------------------
    @GetMapping("/subProject")
    public String subProject(ModelMap mmap){
        return prefix + "/subProject";
    }

    /**
     * 查询订单管理列表
     */
    @PostMapping("/subProjectlist")
    @ResponseBody
    public TableDataInfo subProjectlist(GcProject gysptProject){
    	
    	gysptProject.setDeleteFlag(1);
//    	gysptProject.setProjectManager(getLoginName());
    	List<GcProject> projectlis = gcProjectService.selectGcProjectList(gysptProject);
        
        return getDataTable(projectlis);
    }
    
    //-------------------
    @GetMapping("/subPerson")
    public String subPerson()
    {
        return prefix + "/subPerson";
    }

    /**
     * 查询项目主合同列表
     */
    @PostMapping("/subPersonlist")
    @ResponseBody
    public TableDataInfo subPersonlist(GysptPerson gysptPerson)
    {
        startPage();
        gysptPerson.setDeleteFlag(1);
        List<GysptPerson> list = gysptPersonService.selectGysptPersonList(gysptPerson);
        return getDataTable(list);
    }
    
    //--------------
    @GetMapping("/kqtj")
    public String kqtj(ModelMap mmap){
    	mmap.put("day", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
        return prefix + "/kqtj";
    }

    /**
     * 查询考勤管理列表
     */
    @PostMapping("/kqtjlist")
    @ResponseBody
    public TableDataInfo kqtjlist(GysptKqproject gysptKqproject)
    {
        startPage();
        gysptKqproject.setDeleteFlag(1);
        List<GysptKqproject> list = gysptKqprojectService.selectGysptKqprojectList(gysptKqproject);
        return getDataTable(list);
    }
    
    @GetMapping("/kqtjdetail/{id}/{day}")
    public String kqtjdetail(@PathVariable("id") Long id, @PathVariable("day") String day, ModelMap mmap){
        GysptKqproject gysptKqproject = gysptKqprojectService.selectGysptKqprojectById(id);
        mmap.put("gysptKqproject", gysptKqproject);
        mmap.put("day", day);
        //---
        //当月天数
    	int daySize = DateUtils.getDaysByDate(day);
    	List<Integer> days = new ArrayList<Integer>();
    	Double hj = 0.0;//总合计
    	for(int i =0;i<daySize;i++){
    		days.add(i+1);
    	}
    	mmap.put("daylis", days);
    	
    	//当月人员列表
    	GysptKqygtj gcYgtj = new GysptKqygtj();
    	gcYgtj.setYear(day.substring(0,4));
    	gcYgtj.setMonth(Integer.parseInt(day.substring(5,7))+"");
    	List<GysptKqygtj> peoplelis = gysptKqygtjService.selectGcYgtjList4PeoplePrint(gcYgtj);
    	
    	List<Map> replis = new ArrayList<Map>();
    	for(GysptKqygtj ygtj:peoplelis){
    		
    		GysptKqygtj l_gcYgtj = new GysptKqygtj();
    		l_gcYgtj.setDeleteFlag(1);
    		l_gcYgtj.setYear(day.substring(0,4));
    		l_gcYgtj.setMonth(Integer.parseInt(day.substring(5,7))+"");
    		l_gcYgtj.setPeopleId(ygtj.getPeopleId());
    		List<GysptKqygtj> peopleJcZc = gysptKqygtjService.selectGcYgtjList4PeopledayPrint(l_gcYgtj);
    		
    		List<String> dayJcZc = new ArrayList<String>();
    		double peopleCount = 0.0;
    		double peopleTotal = 0.0;
    		if(peopleJcZc!=null && peopleJcZc.size()>0){
    			for(int i =0;i<daySize;i++){
    				boolean flag = true;
    				Integer lday = i+1;
    				for(GysptKqygtj zcObj:peopleJcZc){
    	    			if(zcObj.getDay().equals(lday.toString())){
    	    				dayJcZc.add(zcObj.getMemo());
    	    				peopleCount+=1;
    	    				peopleTotal+=1;
    	    				flag = false;
    	    				break;
    	    			}
    	    		}
    				
    				if(flag){
    					dayJcZc.add("0");
    				}
    				
    			}
    		}
    		
    		//正常
    		Map rep1 = new HashMap();
    		rep1.put("peopleName", ygtj.getPeopleName());
    		rep1.put("peopleCount", peopleCount);
    		rep1.put("peopleTotal", peopleTotal);
    		rep1.put("peopleJclis", dayJcZc);
    		replis.add(rep1);
    		
    		//小计=合计
    		hj += Double.valueOf(peopleTotal);
    	}
    	
    	List<GysptKqygtj> xjlis = gysptKqygtjService.selectGcYgtjList4Print(gcYgtj);
    	List<String> dayxjs = new ArrayList<String>();
    	if(xjlis!=null && xjlis.size()>0){
	    	for(int i =0;i<daySize;i++){
				boolean flag = true;
				Integer lday = i+1;
				for(GysptKqygtj zcObj:xjlis){
	    			if(zcObj.getDay().equals(lday.toString())){
	    				dayxjs.add(zcObj.getMemo());
	    				flag = false;
	    				break;
	    			}
	    		}
				
				if(flag){
					dayxjs.add("0");
				}
			}
    	}
    	mmap.put("dayxjs", dayxjs);
    	
    	mmap.put("replis", replis);
    	mmap.put("years", day.substring(0,4));
    	mmap.put("month", day.substring(5,7));
    	mmap.put("hj", hj);
        return prefix + "/kqtjview";
    }
    
    @GetMapping("/kqgztview/{id}/{day}")
    public String kqgztview(@PathVariable("id") Long id, @PathVariable("day") String day, ModelMap mmap){
    	GysptKqproject gysptKqproject = gysptKqprojectService.selectGysptKqprojectById(id);
        mmap.put("gysptKqproject", gysptKqproject);
    	
    	GysptKqygtj gcYgtj  =new GysptKqygtj();
    	gcYgtj.setYear(day.substring(0,4));
    	gcYgtj.setMonth(Integer.parseInt(day.substring(5,7))+"");
    	gcYgtj.setProjectId(id);
    	List<GysptKqygtj> gysptKqygtjlis = gysptKqygtjService.selectGcYgtjList4Gzt(gcYgtj);
    	for(GysptKqygtj gtj:gysptKqygtjlis){
    		double memo = Double.valueOf(gtj.getMemo());
    		gtj.setSuosbz(memo*150+"");
    	}
        mmap.put("gysptKqygtjlis", gysptKqygtjlis);
        mmap.put("years", day.substring(0,4));
    	mmap.put("month", (Integer.parseInt(day.substring(5,7))+""));
    	mmap.put("id", id);
    	return prefix + "/kqgztview";
    }
    
    //同步考勤数据至考勤机
    @GetMapping("/subPeople4KQ/{id}")
    @ResponseBody
    public AjaxResult subPeople4KQ(@PathVariable("id") Long id){
//    	try {
//    		GysptKqproject kqobj = gysptKqprojectService.selectGysptKqprojectById(id);
//        	if(kqobj!=null){
//        		GysptDeilikq dlobj = gysptDeilikqService.selectGysptDeilikqById(kqobj.getKqj());
//        		
//        		String AppKey = dlobj.getAppKey();
//        		String AppSecret = dlobj.getAppSecret();
//        		String ext_id = dlobj.getExtId();
//        		
//        		GysptKqworks gysptKqworks = new GysptKqworks();
//        		gysptKqworks.setDeleteFlag(1);
//        		gysptKqworks.setProjectId(kqobj.getId());
//        		List<GysptKqworks> workslis = gysptKqworksService.selectGysptKqworksList(gysptKqworks);
//        		if(workslis!=null && workslis.size()>0){
//        			for(GysptKqworks obj:workslis){
//        				String name = obj.getPeopleName()+"1";
//        				String employee_ext_id = obj.getId().toString();
//        				String mobile = obj.getPhone();
//        				String employee_num = obj.getId().toString();
//        				DeliKQUtils.returnEmployee(AppKey, AppSecret, ext_id, name, employee_ext_id, mobile, employee_num);
//        			}
//        		}
//        	}
//		} catch (Exception e) {
//			// TODO: handle exception
//			e.printStackTrace();
//			return toAjax(0);
//		}
    	
		return toAjax(1);
    }
    
    //同步考勤数据
    @GetMapping("/subKQData/{id}")
    @ResponseBody
    public AjaxResult subKQData(@PathVariable("id") Long id){
    	
//    	GysptKqproject kqobj = gysptKqprojectService.selectGysptKqprojectById(id);
//    	if(kqobj!=null){
//    		GysptDeilikq dlobj = gysptDeilikqService.selectGysptDeilikqById(kqobj.getKqj());
//    		
//    		String AppKey = dlobj.getAppKey();
//    		String AppSecret = dlobj.getAppSecret();
//    		Integer next_id = Integer.parseInt(kqobj.getJig());
//    		
//    		JSONObject jsobj = DeliKQUtils.returnCloudappApi(AppKey, AppSecret, "checkin_query", next_id);
////    		System.out.println(jsobj.getJSONObject("data").get("next_id"));
////    		System.out.println(jsobj.getJSONObject("data").getJSONArray("data"));
//    		next_id = Integer.parseInt(jsobj.getJSONObject("data").get("next_id").toString());
//    		
//    		JSONArray lis = jsobj.getJSONObject("data").getJSONArray("data");
//    		for(int i= 0;i<lis.size();i++){
//    			JSONObject obj = (JSONObject) lis.get(i);
//    			System.out.println("ext_id=="+obj.get("ext_id"));//外部UserId
//    			String ext_id = obj.get("ext_id").toString();
//    			
//    			Date check_time = new Date(Long.parseLong(obj.get("check_time").toString())* 1000);
//    			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//    			String formattedDate = sdf.format(check_time);
//    			System.out.println("check_time=="+ formattedDate);//外部check_time
//    			
//    			addKq(kqobj, ext_id, check_time);
//    		}
//    		
//    		GysptKqproject gysptKqproject = new GysptKqproject();
//    		gysptKqproject.setId(id);
//    		gysptKqproject.setJig(next_id.toString());
//    		gysptKqprojectService.updateGysptKqproject(gysptKqproject);
//    	}
    	
		return toAjax(1);
    }
    
    /**
     * 同步考勤记录
     * @param kqproject 考勤管理
     * @param date		考勤时间
     * @param ext_id	外部传递过去的userId
     * @param formattedDate	打卡时间
     */
    private void addKq(GysptKqproject kqproject,String ext_id,Date check_time){
    	try {
    		Calendar calendar = Calendar.getInstance();
    		calendar.setTime(check_time);
    		 
    		int year = calendar.get(Calendar.YEAR);
    		int month = calendar.get(Calendar.MONTH) + 1;  // 月份从0开始，需要加1
    		int day = calendar.get(Calendar.DAY_OF_MONTH);
    		
    		//项目登记人员
    		GysptKqworks work = gysptKqworksService.selectGysptKqworksById(Long.parseLong(ext_id));
    		
			GysptKqygtj gysptKqygtj = new GysptKqygtj();
			gysptKqygtj.setCreateUser(kqproject.getPhone());
			gysptKqygtj.setUpdateUser(kqproject.getPhone());
			gysptKqygtj.setCreateAt(new Date());
			gysptKqygtj.setUpdateAt(new Date());
			gysptKqygtj.setDeleteFlag(1);
			gysptKqygtj.setMemo("1");
			gysptKqygtj.setStatus(0);
			gysptKqygtj.setProjectId(kqproject.getId());
			gysptKqygtj.setProjectName(kqproject.getName());
			gysptKqygtj.setGysptProjectid(kqproject.getGysptProjectid());
			gysptKqygtj.setPeopleId(work.getPeopleId());
			gysptKqygtj.setPeopleName(work.getPeopleName());
			gysptKqygtj.setYear(String.valueOf(year));
			gysptKqygtj.setMonth(String.valueOf(month));
			gysptKqygtj.setDay(String.valueOf(day));
			gysptKqygtj.setSuosbz(work.getSuosbz());
			gysptKqygtj.setGongz(work.getGongz());
			gysptKqygtjService.insertGysptKqygtj(gysptKqygtj);
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
    }
}